import type { GetUserInfoModel, LoginParams } from '@/api/base/model/userModel'
import type { RoleEnum } from '@/enums/roleEnum'

import { PageEnum } from '@/enums/pageEnum'
import { ACCESS_TOKEN_KEY } from '@/enums/cacheEnum'
import { setAuthCache } from '@/utils/auth'
import { defineStore } from 'pinia'
import { loginApi } from '@/api/base/user'
import { router } from '@/router'

interface UserState {
  userInfo: Nullable<GetUserInfoModel>
  accessToken?: string
  refreshToken?: string
  roleList: RoleEnum[]
  sessionTimeout?: boolean
  lastUpdateTime: number
}

export const useUserStore = defineStore('app-user', {
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    accessToken: undefined,
    refreshToken: undefined,
    // roleList
    roleList: [],
    // Whether the login expired
    sessionTimeout: false,
    // Last fetch time
    lastUpdateTime: 0,
  }),
  actions: {
    setAccessToken(info: string | undefined) {
      this.accessToken = info || '' // for null or undefined value
      setAuthCache(ACCESS_TOKEN_KEY, info)
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean
      },
    ): Promise<GetUserInfoModel | null> {
      try {
        const { goHome = true, ...loginParams } = params
        const data = await loginApi(loginParams)
        // console.log(data)

        // save token
        this.setAccessToken(data)
        return this.afterLoginAction(goHome)
      }
      catch (error) {
        return Promise.reject(error)
      }
    },
    async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
      goHome && (await router.replace(PageEnum.BASE_HOME))
      return null
    }
  }
})
